package com.cjs.angularjs.util.lang;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 日期工具类
 * 
 * @author 仝玉甫
 *
 */
public final class DateUtil {

    private static final Map<DateEnum, DateFormat> formats = new HashMap<DateEnum, DateFormat>();

    static {
        for (DateEnum date : DateEnum.values()) {
            formats.put(date, new SimpleDateFormat(date.getValue()));
        }
    }

    /**获取当前时间 yyyy-MM-dd HH:mm:ss */
    public static String getNow() {
        return formats.get(DateEnum.DATETIME).format(new Date());
    }

    /**获取当前时间*/
    public static String getNow(DateEnum format) {
        return formats.get(format).format(new Date());
    }

    /**转换字符串日期*/
    public static Date parseDate(String date, DateEnum format) {
        try {
            return formats.get(format).parse(date);
        } catch (ParseException e) {
            return null;
        }
    }

    /**日期转换成字符串*/
    public static String parseDate(Date date, DateEnum format) {
        return formats.get(format).format(date);
    }

    /**获取前一天日期*/
    public static String getBeforeDay(DateEnum format) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        return formats.get(format).format(cal.getTime());
    }
}
